package xin.zhiyin.控制.error;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class 错误页面Controller implements ErrorController {
    private static final String PATH = "/error";

    @RequestMapping(value = PATH, method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("jakarta.servlet.error.status_code");
        ModelAndView mav = new ModelAndView();
        if(statusCode == HttpStatus.NOT_FOUND.value()){
            //在src/main/resources/templates/error下寻找404.html页面
            mav.setViewName("error/404");
        }else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()){
            //在src/main/resources/templates/error下寻找500.html页面
            mav.setViewName("error/500");
        }else if(statusCode == HttpStatus.FORBIDDEN.value()){
            //在src/main/resources/templates/error下寻找403.html页面
            mav.setViewName("error/403");
        }else{
            //默认错误页面
            mav.setViewName("error/error");
        }
        return mav;
    }

    public String getErrorPath() {
        return PATH;
    }
}
